package com.foreveross.bsl.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.foreveross.bsl.auth.Auth;
import com.foreveross.bsl.auth.constant.Constant;
import com.foreveross.bsl.auth.integration.ChannelIntegrationBuilder;

/**
 * 原理：请求时把租户去掉（保证静态资源相对路径正确），渲染时再添加租户
 */
public class CtxInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String ticket = (String)request.getSession().getAttribute(Constant.SESSION_KEY);
		if(null == ticket || ticket.isEmpty())
			return super.preHandle(request, response, handler);
		Auth auth = (Auth)ChannelIntegrationBuilder.newInstance().getInfo(ticket);
	
		String reqUri = request.getRequestURI(); // request.getContextPath() + request.getServletPath()
		String ctxUri = request.getContextPath() + "/" + auth.getAccountUsername();

		if(!reqUri.startsWith(ctxUri))
			return super.preHandle(request, response, handler);
		else {
			String s = reqUri.replaceAll(ctxUri, "");
			if(s.isEmpty()) {
				response.sendRedirect(ctxUri+"/mam/appMain/list-view");
				return false;
			} else {
				request.getRequestDispatcher(s).forward(request, response);
				return false;
			}
		}
	}
}
